//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_common

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/dao/fs_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/user_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/fs_api"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/user_api"
	"github.com/dchest/uniuri"
	"github.com/google/uuid"
)

func CreateUser(ctx context.Context, userId, userName, displayName, logoUri, passwd string, testAccount bool, userType user_api.USER_TYPE) error {
	nowTime := time.Now().UnixNano() / 1e6
	//创建默认文件系统
	userFsId := uuid.NewString()
	err := fs_dao.FsInfoDao.Insert(ctx, &fs_dao.FsInfoDbItem{
		FsId:      userFsId,
		OwnerType: int32(fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER),
		OwnerId:   userId,
		Status:    fs_dao.FsStatusDbItem{},
	})
	if err != nil {
		return err
	}
	userMemoFsId := uuid.NewString()
	err = fs_dao.FsInfoDao.Insert(ctx, &fs_dao.FsInfoDbItem{
		FsId:      userMemoFsId,
		OwnerType: int32(fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER),
		OwnerId:   userId,
		Status:    fs_dao.FsStatusDbItem{},
	})
	if err != nil {
		return err
	}
	//创建用户
	err = user_dao.UserInfoDao.Insert(ctx, &user_dao.UserInfoDbItem{
		UserId:   userId,
		UserName: userName,
		BasicInfo: user_dao.BasicUserInfoDbItem{
			DisplayName: displayName,
			LogoUri:     logoUri,
		},
		CreateTime:   nowTime,
		UpdateTime:   nowTime,
		UserFsId:     userFsId,
		UserMemoFsId: userMemoFsId,
		UserType:     uint32(userType),
		TestAccount:  testAccount,
		FeatureInfo: user_dao.FeatureInfoDbItem{
			EnableProject:    true,
			EnableOrg:        true,
			EnableDataView:   true,
			EnableGrowCenter: true,
		},
	})
	if err != nil {
		return err
	}
	if userType == user_api.USER_TYPE_USER_TYPE_INTERNAL {
		//设置密码
		err = user_dao.UserPasswdDao.Set(ctx, userId, passwd)
		if err != nil {
			return err
		}
	}
	//设置secret
	secret := uniuri.NewLenChars(32, []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
	err = user_dao.UserSecretDao.Insert(ctx, &user_dao.UserSecretDbItem{
		UserId: userId,
		Secret: secret,
	})
	if err != nil {
		return err
	}
	return nil
}
